class RouterController < ApplicationController
  before_filter :sys_before_log

  #获取所有固定的信息
  def getRouters
    total = Router.count
    routers = Router.findPage params[:start].to_i,params[:limit].to_i
    jsonStr="{router:"+routers.to_json()+",total:"+total.to_s+"}"
    render :text => jsonStr,:layout => false
  end

  def getAllRouters
    total = Router.count
    routers = Router.find :all
    jsonStr="{root:"+routers.to_json()+",total:"+total.to_s+"}"
    render :text => jsonStr,:layout => false
  end

  def create
    begin
      router = Router.findByTrainNumber params[:trainNumber]
      if router != nil
        info = '交路已存在，请更换！'
      else
        router = Router.new
        router.train_number = params[:trainNumber]
        router.line = params[:line]
        router.length = params[:length]
        router.save!
        info = 'success'
      end
    rescue Exception => e
      logger.info e
      info = '创建异常'
    end

    result = "{success:true,info:\"#{info}\"}"
    render :text => result,:layout => false
  end

  #锁定或解锁，只允许锁定。
  def doLock
    ids= params[:id][1..params[:id].length-2].split(',')
    for id in ids
      router = Router.find(id)
      if router.is_locked == 1
        router.is_locked = 0
      else
        router.is_locked = 1
      end
      router.save!
    end
    info = "success"
    result = "{success:true,info:'#{info}'}"
    render :text=>result, :layout=>false
  end

  def edit
    router = Router.find(params[:id])
    render :text=>router.to_json(),:layout=>false
  end

  def update
    begin
      router = Router.find(params[:id])
      if router.train_number == params[:trainNumber].to_s
        router.line = params[:line]
        router.length = params[:length].to_i
        router.save
        info = 'success'
      else
        routerSN = Router.findByTrainNumber params[:trainNumber]
        if routerSN == nil
          router.train_number = params[:trainNumber]
          router.line = params[:line]
          router.length = params[:length].to_i
          router.save
          info = 'success'
        else
          info = '该交路已存在，请更换！'
        end
      end
    rescue Exception=>e
      logger.info e
      info = '更新异常'
    end
    result = "{success:true,info:\"#{info}\"}"
    render :text=>result, :layout=>false
  end
end
